import request from '@/utils/request';
import {Invoice, InvoiceQueryParams} from './types';
import {getFileUrl, uploadFile} from './file';
import {API_INVOICE} from './config';

/**
 * 获取发票列表
 * @param params 查询参数
 */
export function getInvoiceList(params: InvoiceQueryParams) {
    return request({
        url: API_INVOICE.PAGE,
        method: 'get',
        params
    });
}

/**
 * 获取发票详情
 * @param id 发票ID
 */
export function getInvoiceById(id: string) {
    return request({
        url: API_INVOICE.DETAIL(id),
        method: 'get'
    });
}

/**
 * 创建发票
 * @param data 发票数据
 */
export function createInvoice(data: Invoice) {
    // 处理发票详情字段同步
    if (data.details && data.details.length > 0) {
        data.details.forEach(detail => {
            // 确保specificationModel和specification字段同步
            if (detail.specification && !detail.specificationModel) {
                detail.specificationModel = detail.specification;
            } else if (detail.specificationModel && !detail.specification) {
                detail.specification = detail.specificationModel;
            }

            // 确保unitPrice和price字段同步
            if (detail.price && !detail.unitPrice) {
                detail.unitPrice = detail.price;
            } else if (detail.unitPrice && !detail.price) {
                detail.price = detail.unitPrice;
            }

            // 确保amount和totalAmount字段同步
            if (detail.totalAmount && !detail.amount) {
                detail.amount = detail.totalAmount;
            } else if (detail.amount && !detail.totalAmount) {
                detail.totalAmount = detail.amount;
            }
        });
    }

    // 处理items兼容字段
    if (data.items && !data.details) {
        data.details = data.items;
    }

    return request({
        url: API_INVOICE.CREATE,
        method: 'post',
        data
    });
}

/**
 * 更新发票
 * @param id 发票ID
 * @param data 发票数据
 */
export function updateInvoice(id: string, data: Invoice) {
    // 处理发票详情字段同步
    if (data.details && data.details.length > 0) {
        data.details.forEach(detail => {
            // 确保specificationModel和specification字段同步
            if (detail.specification && !detail.specificationModel) {
                detail.specificationModel = detail.specification;
            } else if (detail.specificationModel && !detail.specification) {
                detail.specification = detail.specificationModel;
            }

            // 确保unitPrice和price字段同步
            if (detail.price && !detail.unitPrice) {
                detail.unitPrice = detail.price;
            } else if (detail.unitPrice && !detail.price) {
                detail.price = detail.unitPrice;
            }

            // 确保amount和totalAmount字段同步
            if (detail.totalAmount && !detail.amount) {
                detail.amount = detail.totalAmount;
            } else if (detail.amount && !detail.totalAmount) {
                detail.totalAmount = detail.amount;
            }
        });
    }

    // 处理items兼容字段
    if (data.items && !data.details) {
        data.details = data.items;
    }

    return request({
        url: API_INVOICE.UPDATE(id),
        method: 'put',
        data
    });
}

/**
 * 删除发票
 * @param id 发票ID
 */
export function deleteInvoice(id: string) {
    return request({
        url: API_INVOICE.DELETE(id),
        method: 'delete'
    });
}

/**
 * 批量删除发票
 * @param ids 发票ID数组
 */
export function batchDeleteInvoice(ids: string[]) {
    return request({
        url: API_INVOICE.BATCH_DELETE,
        method: 'delete',
        data: ids
    });
}

// /**
//  * 获取发票统计数据
//  */
// export function getInvoiceStatistics() {
//     return request({
//         url: API_INVOICE.STATISTICS,
//         method: 'get'
//     });
// }

/**
 * 导出发票
 * @param params 查询参数
 */
export function exportInvoice(params: InvoiceQueryParams) {
    return request({
        url: `${API_INVOICE.BASE}/export`,
        method: 'get',
        params,
        responseType: 'blob',
        headers: {
            'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
    });
}

/**
 * 根据日期范围获取发票
 * @param startDate 开始日期
 * @param endDate 结束日期
 */
export function getInvoiceByDateRange(startDate: string, endDate: string) {
    return request({
        url: `${API_INVOICE.BASE}/date-range`,
        method: 'get',
        params: {startDate, endDate}
    });
}

// /**
//  * 验证发票
//  * @param id 发票ID
//  */
// export function verifyInvoice(id: string) {
//     return request({
//         url: API_INVOICE.VERIFY(id),
//         method: 'post'
//     });
// }

/**
 * 上传发票文件
 * @param file 文件对象
 * @param invoiceId 发票ID（可选）
 * @returns 上传结果
 */
export function uploadInvoiceFile(file: File, invoiceId?: string) {
    return uploadFile(file, invoiceId);
}

// /**
//  * 更新发票文件路径
//  * @param id 发票ID
//  * @param filePath 文件路径
//  * @returns 更新结果
//  */
// export function updateInvoiceFilePath(id: string, filePath: string) {
//     return request({
//         url: `${API_INVOICE.BASE}/${id}/file-path`,
//         method: 'patch',
//         data: {filePath}
//     });
// }

// /**
//  * 部分更新发票信息
//  * @param id 发票ID
//  * @param data 部分发票数据
//  */
// export function updateInvoicePartial(id: string, data: Partial<Invoice>) {
//     return request({
//         url: `${API_INVOICE.BASE}/${id}/partial`,
//         method: 'patch',
//         data
//     });
// }

// 导出文件上传API
export const getInvoiceFileUrl = getFileUrl;

/**
 * 根据发票号码查询
 * @param invoiceNumber 发票号码
 */
export function findInvoiceByNumber(invoiceNumber: string) {
    return request({
        url: `${API_INVOICE.BASE}/number`,
        method: 'get',
        params: {invoiceNumber}
    });
}

/**
 * 根据条件查询发票
 * @param condition 查询条件
 */
export function findInvoiceByCondition(condition: any) {
    return request({
        url: `${API_INVOICE.BASE}/condition`,
        method: 'post',
        data: condition
    });
}

// /**
//  * 搜索发票
//  * @param condition 搜索条件
//  */
// export function searchInvoice(condition: Partial<Invoice>) {
//     return request({
//         url: `${API_INVOICE.BASE}/search`,
//         method: 'post',
//         data: condition
//     });
// }

/**
 * 获取发票关联的订单
 * @param id 发票ID
 */
export function getInvoiceRelatedOrders(id: string) {
    return request({
        url: `${API_INVOICE.BASE}/${id}/related-orders`,
        method: 'get'
    });
}

/**
 * 删除发票关联的订单
 * @param invoiceId 发票ID
 * @param orderId 订单ID
 */
export function deleteInvoiceOrderRelation(invoiceId: string, orderId: string) {
    return request({
        url: `${API_INVOICE.BASE}/${invoiceId}/orders/${orderId}`,
        method: 'delete'
    });
} 